import { showToast } from 'vant'

// AI服务类型
export enum AIServiceType {
  KNOWLEDGE_QA = 'knowledgeQA',
  TEXT_GENERATION = 'textGeneration',
  IMAGE_GENERATION = 'imageGeneration',
  TRANSLATION = 'translation',
  EMOTIONAL_COMPANION = 'emotionalCompanion',
  INFORMATION_QUERY = 'informationQuery',
  RECOMMENDATION = 'recommendation',
  GAME_ENTERTAINMENT = 'gameEntertainment',
  HEALTH_MANAGEMENT = 'healthManagement'
}

// 流式输出回调接口
export interface StreamCallbacks {
  onMessage?: (content: string, isComplete?: boolean) => void
  onComplete?: (fullContent: string) => void
  onError?: (error: any) => void
  onStart?: () => void
}

// AI请求配置
export interface AIRequestConfig {
  userId: number
  message: string
  mode?: string
  options?: Record<string, any>
  enableStream?: boolean
  timeout?: number
  retryCount?: number
}

// AI响应接口
export interface AIResponse {
  success: boolean
  code: number
  data?: any
  message?: string
  error?: string
}

class AIServiceManager {
  private baseURL = 'http://localhost:8082/api/v1'
  private defaultTimeout = 30000
  private defaultRetryCount = 2

  // 统一的AI服务调用方法
  async callAIService(
    serviceType: AIServiceType,
    config: AIRequestConfig,
    callbacks?: StreamCallbacks
  ): Promise<AIResponse> {
    const { enableStream = true, timeout = this.defaultTimeout, retryCount = this.defaultRetryCount } = config

    // 如果启用流式输出，优先使用流式接口
    if (enableStream && callbacks) {
      return this.callStreamService(serviceType, config, callbacks)
    }

    // 使用普通接口
    return this.callNormalService(serviceType, config, retryCount)
  }

  // 流式服务调用
  private async callStreamService(
    serviceType: AIServiceType,
    config: AIRequestConfig,
    callbacks: StreamCallbacks
  ): Promise<AIResponse> {
    try {
      callbacks.onStart?.()

      const streamEndpoint = this.getStreamEndpoint(serviceType)
      const requestBody = this.buildRequestBody(serviceType, config)

      const response = await fetch(`${this.baseURL}${streamEndpoint}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream'
        },
        body: JSON.stringify(requestBody)
      })

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }

      return this.handleStreamResponse(response, callbacks)
    } catch (error) {
      console.error(`流式${serviceType}服务调用失败:`, error)
      callbacks.onError?.(error)
      
      // 流式失败时，尝试普通接口
      return this.callNormalService(serviceType, config, 1)
    }
  }

  // 处理流式响应
  private async handleStreamResponse(
    response: Response,
    callbacks: StreamCallbacks
  ): Promise<AIResponse> {
    const reader = response.body?.getReader()
    const decoder = new TextDecoder()
    let fullContent = ''

    if (!reader) {
      throw new Error('无法读取响应流')
    }

    try {
      while (true) {
        const { done, value } = await reader.read()
        
        if (done) break

        const chunk = decoder.decode(value, { stream: true })
        const lines = chunk.split('\n')

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.slice(6))
              
              if (data.type === 'data' && data.content) {
                fullContent += data.content
                callbacks.onMessage?.(data.content, false)
              } else if (data.type === 'end') {
                callbacks.onMessage?.(fullContent, true)
                callbacks.onComplete?.(fullContent)
                return {
                  success: true,
                  code: 200,
                  data: fullContent
                }
              } else if (data.type === 'error') {
                throw new Error(data.message || '流式输出错误')
              }
            } catch (parseError) {
              console.warn('解析流式数据失败:', parseError)
            }
          }
        }
      }

      // 如果没有收到end事件，也认为成功
      callbacks.onComplete?.(fullContent)
      return {
        success: true,
        code: 200,
        data: fullContent
      }
    } finally {
      reader.releaseLock()
    }
  }

  // 普通服务调用（带重试）
  private async callNormalService(
    serviceType: AIServiceType,
    config: AIRequestConfig,
    retryCount: number
  ): Promise<AIResponse> {
    const endpoint = this.getNormalEndpoint(serviceType)
    const requestBody = this.buildRequestBody(serviceType, config)

    for (let attempt = 1; attempt <= retryCount; attempt++) {
      try {
        const response = await fetch(`${this.baseURL}${endpoint}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestBody),
          signal: AbortSignal.timeout(config.timeout || this.defaultTimeout)
        })

        const result = await response.json()

        if (result.success || result.code === 200) {
          return {
            success: true,
            code: 200,
            data: result.data || result.message || result.answer
          }
        } else {
          throw new Error(result.message || result.error || '服务调用失败')
        }
      } catch (error) {
        console.error(`第${attempt}次尝试${serviceType}服务失败:`, error)
        
        if (attempt === retryCount) {
          return {
            success: false,
            code: 500,
            error: error instanceof Error ? error.message : '服务调用失败'
          }
        }

        // 重试前等待
        await new Promise(resolve => setTimeout(resolve, 1000 * attempt))
      }
    }

    return {
      success: false,
      code: 500,
      error: '服务调用失败'
    }
  }

  // 获取流式端点
  private getStreamEndpoint(serviceType: AIServiceType): string {
    const endpoints: Record<AIServiceType, string> = {
      [AIServiceType.KNOWLEDGE_QA]: '/ai/knowledge-qa/stream',
      [AIServiceType.TEXT_GENERATION]: '/ai/text-generation/stream',
      [AIServiceType.IMAGE_GENERATION]: '/ai/image-generation/stream',
      [AIServiceType.TRANSLATION]: '/ai/translation/stream',
      [AIServiceType.EMOTIONAL_COMPANION]: '/ai/emotional-companion/stream',
      [AIServiceType.INFORMATION_QUERY]: '/ai/information-query/stream',
      [AIServiceType.RECOMMENDATION]: '/ai/recommendation/stream',
      [AIServiceType.GAME_ENTERTAINMENT]: '/ai/game-entertainment/stream',
      [AIServiceType.HEALTH_MANAGEMENT]: '/ai/health-management/stream'
    }
    return endpoints[serviceType] || '/ai/chat/stream'
  }

  // 获取普通端点
  private getNormalEndpoint(serviceType: AIServiceType): string {
    const endpoints: Record<AIServiceType, string> = {
      [AIServiceType.KNOWLEDGE_QA]: '/ai/knowledge-qa',
      [AIServiceType.TEXT_GENERATION]: '/ai/text-generation',
      [AIServiceType.IMAGE_GENERATION]: '/ai/image-generation',
      [AIServiceType.TRANSLATION]: '/ai/translation',
      [AIServiceType.EMOTIONAL_COMPANION]: '/ai/emotional-companion',
      [AIServiceType.INFORMATION_QUERY]: '/ai/information-query',
      [AIServiceType.RECOMMENDATION]: '/ai/recommendation',
      [AIServiceType.GAME_ENTERTAINMENT]: '/ai/game-entertainment',
      [AIServiceType.HEALTH_MANAGEMENT]: '/ai/health-management'
    }
    return endpoints[serviceType] || '/ai/chat'
  }

  // 构建请求体
  private buildRequestBody(serviceType: AIServiceType, config: AIRequestConfig): any {
    const baseBody = {
      userId: config.userId,
      message: config.message,
      mode: config.mode,
      ...config.options
    }

    // 根据服务类型调整请求体
    switch (serviceType) {
      case AIServiceType.IMAGE_GENERATION:
        return {
          ...baseBody,
          prompt: config.message,
          style: config.options?.style || 'realistic',
          size: config.options?.size || '512x512'
        }
      case AIServiceType.TRANSLATION:
        return {
          ...baseBody,
          text: config.message,
          targetLanguage: config.options?.targetLanguage || 'en',
          sourceLanguage: config.options?.sourceLanguage || 'auto'
        }
      default:
        return baseBody
    }
  }

  // 便捷方法：知识问答
  async knowledgeQA(config: AIRequestConfig, callbacks?: StreamCallbacks): Promise<AIResponse> {
    return this.callAIService(AIServiceType.KNOWLEDGE_QA, config, callbacks)
  }

  // 便捷方法：文本生成
  async textGeneration(config: AIRequestConfig, callbacks?: StreamCallbacks): Promise<AIResponse> {
    return this.callAIService(AIServiceType.TEXT_GENERATION, config, callbacks)
  }

  // 便捷方法：图像生成
  async imageGeneration(config: AIRequestConfig): Promise<AIResponse> {
    return this.callAIService(AIServiceType.IMAGE_GENERATION, { ...config, enableStream: false })
  }

  // 便捷方法：翻译
  async translation(config: AIRequestConfig, callbacks?: StreamCallbacks): Promise<AIResponse> {
    return this.callAIService(AIServiceType.TRANSLATION, config, callbacks)
  }

  // 便捷方法：情感陪伴
  async emotionalCompanion(config: AIRequestConfig, callbacks?: StreamCallbacks): Promise<AIResponse> {
    return this.callAIService(AIServiceType.EMOTIONAL_COMPANION, config, callbacks)
  }

  // 便捷方法：信息查询
  async informationQuery(config: AIRequestConfig, callbacks?: StreamCallbacks): Promise<AIResponse> {
    return this.callAIService(AIServiceType.INFORMATION_QUERY, config, callbacks)
  }

  // 便捷方法：智能推荐
  async recommendation(config: AIRequestConfig, callbacks?: StreamCallbacks): Promise<AIResponse> {
    return this.callAIService(AIServiceType.RECOMMENDATION, config, callbacks)
  }

  // 便捷方法：游戏娱乐
  async gameEntertainment(config: AIRequestConfig, callbacks?: StreamCallbacks): Promise<AIResponse> {
    return this.callAIService(AIServiceType.GAME_ENTERTAINMENT, config, callbacks)
  }

  // 便捷方法：健康管理
  async healthManagement(config: AIRequestConfig, callbacks?: StreamCallbacks): Promise<AIResponse> {
    return this.callAIService(AIServiceType.HEALTH_MANAGEMENT, config, callbacks)
  }

  // 获取服务状态
  async getServiceStatus(): Promise<Record<string, boolean>> {
    try {
      const response = await fetch(`${this.baseURL}/ai/status`)
      const result = await response.json()
      return result.data || {}
    } catch (error) {
      console.error('获取服务状态失败:', error)
      return {}
    }
  }

  // 获取用户使用统计
  async getUserStats(userId: number): Promise<any> {
    try {
      const response = await fetch(`${this.baseURL}/ai/stats/${userId}`)
      const result = await response.json()
      return result.data || {}
    } catch (error) {
      console.error('获取用户统计失败:', error)
      return {}
    }
  }
}

// 导出单例
export const aiServiceManager = new AIServiceManager()

// 导出便捷函数
export const useAIService = () => {
  return {
    callAI: aiServiceManager.callAIService.bind(aiServiceManager),
    knowledgeQA: aiServiceManager.knowledgeQA.bind(aiServiceManager),
    textGeneration: aiServiceManager.textGeneration.bind(aiServiceManager),
    imageGeneration: aiServiceManager.imageGeneration.bind(aiServiceManager),
    translation: aiServiceManager.translation.bind(aiServiceManager),
    emotionalCompanion: aiServiceManager.emotionalCompanion.bind(aiServiceManager),
    informationQuery: aiServiceManager.informationQuery.bind(aiServiceManager),
    recommendation: aiServiceManager.recommendation.bind(aiServiceManager),
    gameEntertainment: aiServiceManager.gameEntertainment.bind(aiServiceManager),
    healthManagement: aiServiceManager.healthManagement.bind(aiServiceManager),
    getServiceStatus: aiServiceManager.getServiceStatus.bind(aiServiceManager),
    getUserStats: aiServiceManager.getUserStats.bind(aiServiceManager)
  }
}
